package com.yeyuanqi.hottop.controller;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yeyuanqi.hottop.common.Result;
import com.yeyuanqi.hottop.common.dto.LoginDto;
import com.yeyuanqi.hottop.entity.RoleUser;
import com.yeyuanqi.hottop.entity.SysUser;
import com.yeyuanqi.hottop.service.SysUserService;
import com.yeyuanqi.hottop.untils.JwtUtils;
import com.yeyuanqi.hottop.untils.BCryptUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 登录登出注册控制器
 *
 * @author yeyuanqi
 * @date  2022/02/26
 */
@RestController
public class AccountController {

    //Lazy延迟初始化,防止bean不能被所有的BeanPostProcessors处理
//    @Lazy
    @Autowired
    JwtUtils jwtUtils;

//    @Lazy
    @Autowired
    BCryptUtils bCryptUtils;

//    @Lazy
    @Autowired
    SysUserService userService;

    /**
     * 登录请求处理
     */
    @CrossOrigin
    @PostMapping("/login")
    public Result login(@Validated @RequestBody LoginDto loginDto, HttpServletResponse response) {

        SysUser user = userService.getOne(new QueryWrapper<SysUser>().eq("user_name", loginDto.getUsername()));
        //判断传进来的参数值是否不为空值
        if (user == null ) {
            return Result.fail("用户名不存在！");
        }
        if (!bCryptUtils.matchesPassword(loginDto.getPassword(),user.getPassword())) {
            return Result.fail("密码错误！");
        }
        if("1".equals(user.getStatus())){
            return Result.fail("账户已被禁用");
        }
        if("2".equals(user.getDelFlag())){
            return Result.fail("账户已被删除");
        }
        String jwt = jwtUtils.generateToken(user.getUserId(),user.getUserName());
        response.setHeader("Authorization", jwt);
        response.setHeader("Access-Control-Expose-Headers", "Authorization");
        // 用户可以另一个接口
        return Result.succ(MapUtil.builder()
                .put("id", user.getUserId())
                .put("username", user.getUserName())
                .put("avatar", user.getAvatar())
                .put("email", user.getEmail())
                .put("role", user.getRole())
                .map()
        );

    }

    /**
     * 登出请求处理
     */
    @GetMapping("/logout")
    @RequiresAuthentication
    public Result logout() {
        SecurityUtils.getSubject().logout();
        return Result.succ("退出成功");
    }



    /**
     * 登录请求处理
     */
    @CrossOrigin
    @PostMapping("/register")
    public Result register(@Validated @RequestBody LoginDto loginDto, HttpServletResponse response) {

        SysUser register = userService.getOne(new QueryWrapper<SysUser>().eq("user_name", loginDto.getUsername()));
        //判断传进来的参数值是否不为空值
        if (register != null ) {
            return Result.fail("用户已注册！");
        }

        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateNowStr = sdf.format(d);
        SysUser user = new SysUser();
        RoleUser roleUser = new RoleUser();
        roleUser.setRole_id(2l);
        try {
            user.setUserName(loginDto.getUsername());
            user.setPassword(bCryptUtils.encryptPassword(loginDto.getPassword()));
            user.setNickName(user.getUserName());
            //设置默认头像
            user.setAvatar("/profile/avatar/2022/02/23/4991869b-df26-407b-a0d8-19da8110da34.jpeg");
            user.setCreateTime(sdf.parse(dateNowStr));
            if (userService.save(user)){
                roleUser.setUser_id(user.getUserId());
                userService.addRoleUser(roleUser);
                return Result.succ("注册成功");
            }else{
                return Result.fail("注册失败");
            }
        } catch (Exception e){
            return Result.fail(e.getMessage());
        }
    }
}
